package com.pubinfo.passbook.data.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.merge.OnceAbsoluteMergeStrategy;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.pubinfo.passbook.common.entity.*;
import com.pubinfo.passbook.common.mapper.TFileEnclosureFtpMapper;
import com.pubinfo.passbook.common.model.bo.witeoff.MedicineOnJobOrRetireBO;
import com.pubinfo.passbook.common.model.dto.witeoff.Artificial;
import com.pubinfo.passbook.common.model.ruler.Reimbursement;
import com.pubinfo.passbook.common.model.ruler.ReimbursementExcel;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.data.service.TFileInfoService;
import com.pubinfo.passbook.common.service.ruler.MergeStrategy.MyMergeStrategy;
import com.pubinfo.passbook.data.service.CreateExcelService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class CreateExcelServiceImpl implements CreateExcelService {

    @Autowired
    TFileInfoService tFileInfoService;
    @Autowired
    TPassbookService tPassbookService;

    @Value("${file.uploadFolder}")
    private String filePath;

    @Override
    public TFileEnclosureFtp createExcelByClass(List<Reimbursement> reimbursement) {
        //文件保存地址，还没具体配置现在和附件放在同一目录下，命名是createExcelByClass+当前时间戳
        String fileName = "ReimbursementDocument" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(filePath + fileName, Reimbursement.class)
                .head(head())
                .sheet()
                .registerWriteHandler(style())
                .registerWriteHandler(new MyMergeStrategy(reimbursement))
                .doWrite(createReimbursement(reimbursement));
        File excelFile = new File(filePath + fileName);
        TFileInfo tFileInfo = new TFileInfo();
        tFileInfo.setName(excelFile.getName());
        tFileInfo.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        tFileInfo.setSize(excelFile.length());
        tFileInfo.setPath(filePath + fileName);
        tFileInfo.setCreateBy("system");
        tFileInfo.setType(3);
        tFileInfo.setIsDelete(1);
        return tFileInfoService.saveFile(tFileInfo);
//        return new TFileFtp();
    }

    @Override
    public TFileEnclosureFtp createShenGongSiExcel(List<TPassbook> tPassbooks, List<TSourceArtificial> artificials) {

        String fileName = "ReimbursementList" + System.currentTimeMillis() + ".xlsx";

        List<ReimbursementExcel> reimbursementExcels = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tPassbooks)) {
            tPassbooks.stream().forEach(tPassbook -> reimbursementExcels.add(new ReimbursementExcel(tPassbook)));
        }
        if (CollectionUtils.isNotEmpty(artificials)) {
            artificials.stream().forEach(artificial -> reimbursementExcels.add(new ReimbursementExcel(artificial)));
        }

        ReimbursementExcel reimbursementExcel=new ReimbursementExcel("合计");

        reimbursementExcels.forEach(reimbursementExcel1 ->
                {
                    reimbursementExcel.setTotalAmount(new BigDecimal(reimbursementExcel1.getTotalAmount()).add(new BigDecimal(reimbursementExcel.getTotalAmount())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setSelfpaymentCare(new BigDecimal(reimbursementExcel1.getSelfpaymentCare()).add(new BigDecimal(reimbursementExcel.getSelfpaymentCare())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setSelfpaymentCost(new BigDecimal(reimbursementExcel1.getSelfpaymentCost()).add(new BigDecimal(reimbursementExcel.getSelfpaymentCost())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setDisbursedExpenses(new BigDecimal(reimbursementExcel1.getDisbursedExpenses()).add(new BigDecimal(reimbursementExcel.getDisbursedExpenses())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setFundPayAmount(new BigDecimal(reimbursementExcel1.getFundPayAmount()).add(new BigDecimal(reimbursementExcel.getFundPayAmount())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setCurrPayment(new BigDecimal(reimbursementExcel1.getCurrPayment()).add(new BigDecimal(reimbursementExcel.getCurrPayment())).setScale(2, RoundingMode.HALF_UP).toString());
                    reimbursementExcel.setReimbursableSum(new BigDecimal(reimbursementExcel1.getReimbursableSum()).add(new BigDecimal(reimbursementExcel.getReimbursableSum())).setScale(2, RoundingMode.HALF_UP).toString());
                });

        reimbursementExcels.add(reimbursementExcel);

        OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(reimbursementExcels.size()+1, reimbursementExcels.size()+1, 0, 5);

        EasyExcel.write(filePath + fileName, ReimbursementExcel.class)
                .sheet()
                .registerWriteHandler(style())
                .registerWriteHandler(onceAbsoluteMergeStrategy)
                .doWrite(reimbursementExcels);
        File excelFile = new File(filePath + fileName);
        TFileInfo tFileInfo = new TFileInfo();
        tFileInfo.setName(excelFile.getName());
        tFileInfo.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        tFileInfo.setSize(excelFile.length());
        tFileInfo.setPath(filePath + fileName);
        tFileInfo.setCreateBy("system");
        tFileInfo.setType(3);
        tFileInfo.setIsDelete(1);
        return tFileInfoService.saveFile(tFileInfo);
    }

    //生成头
    private List<List<String>> head() {
        String[] headList = {"序号", "员工姓名", "部门", "员工类型", "供属姓名", "供属关系", "工龄", "住院/门诊",
                "是否特殊病种", "单据数量", "医疗费总额", "核报金额"};
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head = new ArrayList<String>();
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy年MM月");
        head.add("中国电信浙江公司医药费报销单");
        head.add(format.format(date));
        for (int i = 0; i < headList.length; i++) {
            List<String> headCopy = new ArrayList<>(head);
            headCopy.add(headList[i]);
            list.add(headCopy);
        }
        return list;
    }

    //生成合计行
    private List<Reimbursement> createReimbursement(List<Reimbursement> reimbursements) {
        Reimbursement hospitalizationReimbursement = reimbursements.get(0);
        Reimbursement outpatientDepartmentReimbursement = reimbursements.get(1);
        Reimbursement reimbursement = new Reimbursement((Integer.valueOf(hospitalizationReimbursement.getPassbookNub()) + Integer.valueOf(outpatientDepartmentReimbursement.getPassbookNub()))
                , hospitalizationReimbursement.getTotalAmount().add(outpatientDepartmentReimbursement.getTotalAmount())
                , hospitalizationReimbursement.getApprovedAmount().add(outpatientDepartmentReimbursement.getApprovedAmount()));
        reimbursements.add(2, reimbursement);
        return reimbursements;
    }

    //生成样式
    private HorizontalCellStyleStrategy style() {
        WriteFont headWriteFont = new WriteFont();
        //字体为11号
        headWriteFont.setFontHeightInPoints((short) 11);

        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为白色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        headWriteCellStyle.setWriteFont(headWriteFont);

        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        //字体为11号
        contentWriteCellStyle.setWriteFont(headWriteFont);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);


        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        return horizontalCellStyleStrategy;
    }
}
